/* eslint-disable */
import axios from 'axios'
import store from '@/vuex'
import router from '../router'
import utilVue from '../util/utilVue.js'
let proxyApi = process.env.VUE_APP_BASE_API

function getBaseUrl() {
  if (proxyApi .indexOf('http') != -1) {
    return '/api/'
  }
  return location.origin + proxyApi
}
// create an axios instance
const service = axios.create({
  baseURL: getBaseUrl(), // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 120000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  (config) => {
    // do something before request is sent

    if (store.getters.currentUser) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = sessionStorage.getItem('X-Token')
      config.headers['warehouseId'] = store.getters.currentWarehouse.id
      config.headers['requestType'] = 'spdpc'
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response) => {
    let {headers, data} = response
    let contentType = headers['content-type']
    if (contentType && contentType.indexOf('application/json') == -1) {
      return response
    }

    let isValidexception = headers && '1' == headers.validexception

    const res = data
    // if the custom code is not 0, it is judged as an error.
    if (res.success) {
      return res
    }
    utilVue.loadHide()
    if (res.success == undefined) { //如果未定义，直接返回
      return res
    }

    global.utilMessage.error(res.msg)

    //下面功能尚未实现，暂时注释掉
    // return Promise.reject(new Error(res.msg || 'Error'))
    // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
    if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
    }
    return res
    // return Promise.reject(new Error(res.msg || 'Error'))
  },
  (error) => {
    utilVue.loadHide()
    let response = error?error.response:null
    let status = response?response.status:null
    let data = response?response.data:null
    let isValidexception = response && response.headers && '1' == response.headers.validexception
    if (data && data.data && data.data.needLogin) {
      if (window.logoutOutAlert && window.logoutOutAlert == 1) {
        return
      }
      window.logoutOutAlert = 1
      global.utilMessage.alertFail('会话超时，请重新登录!', () => {
        router.push('/login', () => {
          window.logoutOutAlert = 0
          global.utils.toLogin()
        })
      })

      return Promise.reject(error)
    }
    let msg='未知异常'
    if(!status){
      msg= '网络连接异常，请检查本地网络是否连接'
    }else if(status == 500){
      if(response.data.msg){
        msg= response.data.msg
      }else if(response.data.message){
        msg= response.data.message
        if(msg.indexOf('服务器异常') == -1) msg='服务器异常，原因:'+msg
      }else if(typeof(response.data) == 'string'  && response.data.indexOf('Proxy error') != -1){
        msg= '服务器暂时无法访问，请稍候重试'
      }
    }else if(status == 502){
      msg= '代理服务器暂时不可以使用，请稍候重试'
    }

    global.utilMessage.error(msg)
    return Promise.reject(error)
  }
)

export default service
